package com.mew.chess.core.game.qmcs.game;

import cn.hutool.core.util.StrUtil;
import com.mew.chess.core.common.handler.ChessStart;
import com.mew.chess.core.common.handler.ChessStartAnnotation;
import com.mew.chess.core.game.qmcs.game.common.QmcsConstantValue;
import com.mew.chess.core.game.qmcs.game.common.QmcsRoute;
import com.mew.chess.core.game.qmcs.game.common.QmcsTableUtil;
import com.mew.common.dc.redis.GameRoomRedisService;
import com.mew.common.entity.config.Room;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@ChessStartAnnotation("QMCS")
@Service
@Slf4j
public class QmcsStartService implements ChessStart {

    @Autowired
    private GameRoomRedisService gameRoomRedisService;

    @Override
    public void initializeGame(int gameId) throws Exception {
        initialConfig(gameId);
        addRoomManager(gameId);
        log.info("Fishing gameId:{} ---start-success-----", gameId);
    }

    private void initialConfig(int gameId) throws Exception {

        QmcsGameManager gameManager = QmcsGameManager.getInstance();
        gameManager.setGameId(gameId);

        QmcsRoute.initRoutes( gameManager);

        if (null == gameManager.getQmcsRoutes() || gameManager.getQmcsRoutes().isEmpty()){
            throw new Exception("Fishing not config info");
        }

        gameManager.initallZebraExecutorGroup();

    }


    private void addRoomManager(int gameId)throws Exception{
        List<Room> roomList = gameRoomRedisService.findRoomByGameId(gameId);
        if (null == roomList || roomList.isEmpty()){
            throw new Exception("Start Game "+ gameId +" room is null");
        }

        for (Room room : roomList){
            QmcsGameManager.getInstance().putController(initializeRoomManager(room));
        }
    }

    private QmcsRoomManager initializeRoomManager(Room room){
        QmcsRoomManager roomController = new QmcsRoomManager(room.getGameId(), room.getId(), room.getRoomType());
        roomController.setBets(StrUtil.splitToInt(room.getBetArrs(), ","));
        QmcsTableUtil.buildTable(roomController, QmcsConstantValue.INIT_TABLE_SIZE);
        return roomController;
    }
}
